package hevs.utils;



import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;


import android.content.Context;
import android.util.Log;

/**
 * This class is for connection management
 * @author Jonathan Moreira, Jun Yang, Natal Venetz, Ivan Samardziev
 *
 */
public class ConnectionManager {

	private final static String URL = "http://sub.naven.ch/sobjal/webservice/";
	//private static UserData userData;
	private static String errorMessage ="";
	
	/**
	 * Method used to send a http post request to the server 
	 * and get the server's response in JSONArray
	 * @param servicePage
	 * @param nameValuePairs
	 * @return jArray
	 */
	public static JSONArray sendhttpPost(String servicePage, ArrayList<BasicNameValuePair> nameValuePairs)
	{
		// get the response 
		InputStream is = null;
		//get the result of the action
		String result = "";
		// JSON Array to return 
		JSONArray jArray = null;
		
		//http Post
		try
		{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(URL + servicePage);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch(Exception e)
		{
			Log.e("log_tag", "Error in http connection "+e.toString());
			setErrorMessage("Error internet connection");
			return null;
		}
		
		
		// response string getter
		try
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null)
			{
				sb.append(line + "\n");
			}

			is.close();

			result=sb.toString();
			Log.i("response_tag", result);
		}
		catch(Exception e)
		{
			Log.e("log_tag", "Error converting result "+e.toString());
			setErrorMessage("Error converting result ");
			return null;
		}

		//parse json data
		try
		{
			 jArray = new JSONArray(result);
		}
		catch(JSONException e)
		{
			Log.e("log_tag", "Error parsing data "+e.toString());
			setErrorMessage("Error server response : " + result);
			return null;
		}
	
		return jArray;
		
	}
	
	/**
	 * Method used to get the smart objects by user id
	 * @param idUser
	 * @param context
	 * @return jArrayObjects
	 */
	public static JSONArray getObjectsByIdUser(int idUser, Context context)
	{
		//prepare aa list clear
		//userData = UserData.getInstance();
		//userData.clearSmartObjectList();
		
		//insert the userID in the list
		//userData.setIdUser(idUser);
		
		// parameters
		ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();

		nameValuePairs.add(new BasicNameValuePair("userId",""+idUser));
		JSONArray jArrayObjects = ConnectionManager.sendhttpPost("objects.php", nameValuePairs);

		if(jArrayObjects != null)
		{
			try {
				if(jArrayObjects.getJSONObject(0).getInt("idSmartObject") > 0)
				{
					for(int i=0;i<jArrayObjects.length();i++)
					{
						int id = jArrayObjects.getJSONObject(i).getInt("idSmartObject");
						String name = jArrayObjects.getJSONObject(i).getString("name");
						int typeId = jArrayObjects.getJSONObject(i).getInt("idSmartObjectType");
				//		userData.addSmartObject(new SmartObject(id,name,typeId));
					} 
				}
				else
				{
					Error.noRobotInfo(context);
				}
			} 
			catch (JSONException e) 
			{
				e.printStackTrace();
			}
		}
		else
		{
			Error.serviceFunctionError(context);
		}
		
		return jArrayObjects;
	}

	/**
	 * Method used to set the error message to application
	 * @param errorMessage
	 */
	public static void setErrorMessage(String errorMessage) 
	{
		ConnectionManager.errorMessage = errorMessage;
	}

	/**
	 * Method used to get the error message of application
	 * @return errorMessage
	 */
	public static String getErrorMessage() 
	{
		return errorMessage;
	}
	
	
}
